package com.magictower.primary.activity;

import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.TextView;

import com.magictower.primary.R;
import com.magictower.primary.db.dao.AddressDao;
import com.magictower.primary.utils.ToastUtils;

/**
 * @author kejunzhan
 * @since 2017/12/13
 */

public class AddressActivity extends AppCompatActivity {

    private EditText etNumber;
    private TextView tvResult;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        etNumber = (EditText) findViewById(R.id.et_number);
        tvResult = (TextView) findViewById(R.id.tv_result);

        etNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String result = AddressDao.getAddress(s.toString().trim());
                tvResult.setText(result);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public void query(View view) {
        String number = etNumber.getText().toString().trim();
        if (!TextUtils.isEmpty(number)) {
            String result = AddressDao.getAddress(number);
            tvResult.setText(result);
        } else {
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.shake);
            etNumber.startAnimation(animation);
            vibrate();
            ToastUtils.showToast(this, "请输入查询号码");
        }

    }

    /**
     * 手机震动, 需要权限 android.permission.VIBRATE
     */
    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(new long[]{1000, 2000, 1000, 3000}, -1);
        // 先等待1秒,再震动2秒,再等待1秒,再震动3秒,
        // 参2等于-1表示只执行一次,不循环,
        // 参2等于0表示从头循环,
        // 参2表示从第几个位置开始循环
        //vibrator.cancel();//取消震动
    }
}
